﻿using System;
using DavidJalbert.TinyCarControllerAdvance;
using UnityEngine;
using WorldMapBase.Tile.Pool;
using Yoozoo.Gameplay.Liberty.AI;

namespace Yoozoo.Gameplay.Liberty.Pool
{
    public class LibertyNpcPool : ObjectPool<GameObject>
    {
        private int _initNum;
        protected GameObject _originObject;

        public int NpcId;
        public int NpcType;
        
        public LibertyNpcPool(int npcId, int initNum, int capacity,GameObject originObject) : 
            base(capacity,true,3,1,10)
        {
#if UNITY_EDITOR
            _name = "街道Npc对象池: " + originObject.name;
#endif
            _initNum = initNum;
            _originObject = originObject;
            NpcId = npcId;
        }

        public void PreInit()
        {
            OnInit(_initNum);
        }

        public void PreInitASync(Action<int> callBack)
        {
            OnInitAsync(_initNum, () =>
            {
                callBack?.Invoke(NpcId);
            });
        }
        
        protected override GameObject ConstructItem()
        {
            if (_originObject == null)
            {
                UnityEngine.Debug.LogError("街道Npc对象池 _originObject 为空");
                return null;
            }
            
            GameObject npc = 
                GameObject.Instantiate(_originObject,
                    Vector3.zero,
                    Quaternion.identity,
                    LibertyAIUtils.LibertyManager.NpcManager.transform);

            if (NpcType == 2)
            {
                var carPlayer = npc.GetComponentInChildren<TCCAPlayer>(true);
                if (carPlayer)
                {
                    carPlayer.Init();
                }

                var vehicleAI = npc.GetComponent<VehicleAI>();
                if (vehicleAI)
                {
                    vehicleAI.Init();
                }
                npc.SetActive(true);
            }

            if (NpcType == 3)
            {
                var carPlayer = npc.GetComponentInChildren<TCCAPlayer>(true);
                if (carPlayer)
                {
                    carPlayer.Init();
                }
                npc.SetActive(true);
            }
            npc.SetActive(false);
            return npc;
        }
        
        protected override void BeforeRecover(GameObject obj)
        {
            obj.transform.parent = LibertyAIUtils.LibertyManager.NpcManager.transform;
            obj.SetActive(false);
        }

        protected override void OnRemoveItem(GameObject obj)
        {
            GameObject.Destroy(obj);
        }

        public override void Destroy()
        {
            base.Destroy();
            _originObject = null;
        }
    }
}